<template>
  <!-- 服务开通弹窗  -->
  <el-dialog class="pick-dialog" :title="ruleForm.isFirst==1?'开通服务':'续费服务'" :visible.sync="dialogVisible" :close-on-click-modal="false" append-to-body width="660px">
    <div class="">
      <!-- {{ ruleForm }} -->
      <div class="" style="padding: 10px 0;" v-if="ruleForm.businessId==5492">
        开通竞拍市场须先开通以下功能：1.回收管理；2.客服即时通讯；3.店铺完成实名认证。
      </div>
      <el-descriptions :labelStyle="{width:'100px'}" :title="ruleForm.isFirst==1?'开通服务':'续费服务'" border :column='1'>
        <el-descriptions-item label="服务名称">{{ruleForm.businessName}}</el-descriptions-item>
        <!-- <el-descriptions-item label="可对接游戏">{{ruleForm.gameNames}}</el-descriptions-item> -->
        <el-descriptions-item :label="ruleForm.isFirst==1?'开通时长':'续费时长'">
          <div>
            <span v-if="groupItem.buyWay==1&&(ruleForm.businessId!=5492||(ruleForm.businessId==5492&&ruleForm.isFirst==1))">免费开通</span>
            <span v-if="ruleForm.businessId==5492&&ruleForm.isFirst==2">长期开通</span>
            <span v-if="userInfo.userId!=1&&groupItem.buyWay==2">{{groupItem.minMonthDuration}}个月（{{ruleForm.isFirst==1?'首次开通':'手动续费'}}默认{{groupItem.minMonthDuration}}个月，自动续费每次1个月）</span>
            <span v-if="groupItem.buyWay==3">长期开通</span>
            <span v-if="userInfo.userId==1&&groupItem.buyWay==2">
              <el-input-number @change="monthChange" style="width:130px" v-model="ruleForm.openMonth" :min="1" :max="100" label="label"></el-input-number>月
            </span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="所需虞豆" v-if="groupItem.buyWay!=1||ruleForm.businessId==5492">
          <div>
            <span v-if="ruleForm.businessId==5492&&ruleForm.isFirst==2">{{ jjscguize.againCost&&jjscguize.againCost.dictValue }}</span>
            <div v-else>
              <span v-if="userInfo.userId!=1">{{ruleForm.cost}}</span>
              <el-input v-else type="number" style="width:130px" v-model="ruleForm.cost" :min="0" :max="100" label="label"></el-input>
              <span v-if="groupItem.buyWay==2">（开通：{{groupItem.monthAmount}}虞豆/月，续费：{{groupItem.renewalAmount}}虞豆/月）</span>
            </div>

          </div>
        </el-descriptions-item>
        <el-descriptions-item label="当前虞豆">
          {{campNumber}}
        </el-descriptions-item>
        <el-descriptions-item label="自动续费" v-if="groupItem.buyWay==2">
          <el-switch v-model="ruleForm.isAuto" :active-value="1" :inactive-value="2" active-color="#13ce66" inactive-color="#ff4949">
          </el-switch>
        </el-descriptions-item>
      </el-descriptions>
      <div class="tip" style="margin-top: 10px;" v-if="ruleForm.businessId==5492">
        提示：竞拍市场首次开通免费，如果在一个自然月内未达到交易要求，系统将关闭你的竞拍市场交易权限。
        <span style="color: dodgerblue; cursor: pointer;" @click="openJingjiaGuize">点击查看竞拍规则</span>
      </div>
      <div class="tip" style="margin-top: 10px;" v-if="ruleForm.businessId==5496">
        提示：开通APP推送的前提是自营商城APP已经上架各大应用市场，开通前请先咨询商务。
      </div>
      <div class="center">
        <el-button @click="close('ruleForm')">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">
          <span v-if="ruleForm.isFirst==1">确认开通</span>
          <span v-if="ruleForm.isFirst==2&&ruleForm.businessId==5492">确认开通</span>
          <span v-else-if="ruleForm.isFirst==2">确认续费</span>
        </el-button>
      </div>
      <chongzhi ref="chongzhi"></chongzhi>
      <authTipDialog ref="authTipDialog"></authTipDialog>
      <authDialogVue ref="authDialogVue"></authDialogVue>
      <jingjiaguizeDialog ref="jingjiaguizeDialog"></jingjiaguizeDialog>

    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from "vuex";
import valueAddedServices from "@/api/shanghuduan/valueAddedServices";
import chongzhi from "@/views/tenantPages/moneys/components/chongzhijifen.vue";
import authTipDialog from "./authTipDialog.vue";
import authDialogVue from "../../views/tenantPages/shopManage/shopCenter/authDialog.vue";
import jingjiaguizeDialog from "../../views/jingpaishichang/components/jingjiaguizeDialog.vue";
export default {
  name: "",
  props: ["tenantId", "campNumber","serverIndex"],
  components: { chongzhi, authTipDialog, authDialogVue, jingjiaguizeDialog },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      type: "",
      ruleForm: {
        type: "1",
        businessId: "",
        businessName: "",
        openMonth: "",
        isAuto: "",
        cost: "",
        isFirst: 1,
      },
      rules: {},
      from: "", //来源
      activeInfo: "",
      monthList: [],
      activeIndex: 0,
      groupItem: {},
      jjscguize: {},
      jingpaiguizeIsShow: false,
    };
  },
  created() {},
  methods: {
    async open(item, isFirst, type = 1) {
      // console.log("%c Line:95 🌽 item", "color:#3f7cff", item);
      this.groupItem = { ...item };
      //console.log("%c Line:102 🍯 item", "color:#42b983", item);
      this.loading = false;
      let costNum = 0;
      if (this.groupItem.buyWay == 2) {
        if (isFirst == 1) {
          // 开通
          costNum =
            this.groupItem.minMonthDuration * this.groupItem.monthAmount;
        } else {
          costNum =
            this.groupItem.minMonthDuration * this.groupItem.renewalAmount;
        }
      } else if (this.groupItem.buyWay == 3) {
        costNum = this.groupItem.monthAmount;
      }
      this.ruleForm = {
        type: type,
        businessId: this.groupItem.groupId || this.groupItem.id,
        businessName: this.groupItem.groupName || this.groupItem.name,
        openMonth:
          this.groupItem.buyWay == 2 ? this.groupItem.minMonthDuration : "",
        isAuto: 1,
        autoMonth: 1,
        cost: costNum,
        isFirst: isFirst,
      };
      if (isFirst == 2) {
        this.ruleForm.valueAddedServiceId = this.groupItem.id;
        if (this.ruleForm.businessId == 5492) {
          await this.getJJSCguize();
          // 竞拍市场
          this.ruleForm.cost = this.jjscguize.againCost.dictValue;
        }
      }
      this.dialogVisible = true;
    },
    //获取竞价回收规则字典
    async getJJSCguize() {
      const res = await this.getDicts("biddingRule");
      if (res.data && res.data.length) {
        this.jjscguize = this.arrayToObject(res.data, "dictLabel");
      }
    },
    // 打开竞价规则
    openJingjiaGuize() {
      this.$refs.jingjiaguizeDialog.open();
    },
    // 月数改变
    monthChange(e) {
      this.groupItem.openMonth = e;
      this.ruleForm.cost =
        this.groupItem.openMonth * this.groupItem.monthAmount;
    },
    delay(time) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(true);
        }, time);
      });
    },
    submitForm() {
      // this.$refs.authTipDialog.open()
      // return
      this.ruleForm.tenantId = this.tenantId;
      const loading = this.$loading();
      valueAddedServices
        .openValueAddedServices(this.ruleForm)
        .then(async (res) => {
          loading.close();
          if (res.code == 200) {
            this.$alert("操作成功！")
            // this.$message.success("操作成功！");
          }
          this.$store.dispatch("GetInfo", true);
          this.$emit("success");
           if(this.serverIndex) {
            this.close();
            return}
          if (this.ruleForm.businessId == 5490 && this.ruleForm.type == 1) {
            // 开通回收管理
            this.$refs.authTipDialog.open();
          } else {
            if (res.code == 200) {
              if (this.userInfo && this.userInfo.userId == 1) {
                this.$alert("开通成功，请提醒该商户刷新网站以获取最新权限！");
              } else {
                if (this.ruleForm.businessId == 5483) {
                  // 开通自营商城
                  this.$confirm(
                    "开通成功，网站刷新后请在“设置管理>手机端设置”进行商城配置！",
                    "提示",
                    {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                    }
                  )
                    .then(() => {
                      location.reload();
                    })
                    .catch(() => {
                      location.reload();
                    });
                } else {
                  this.$confirm(
                    "开通成功，将刷新网站以获取最新权限！",
                    "提示",
                    {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                    }
                  )
                    .then(() => {
                     
                         location.reload();
                     
                    })
                    .catch(() => {
                         location.reload();
                    });
                }
              }
            }
          }
          this.close();
        })
        .catch((err) => {
          console.log("%c Line:141 🍆 err", "color:#465975", err.Error);
          loading.close();
          const str = String(err);
          if (str.includes("余额")) {
            this.chongzhijifen();
          } else if (str.includes("回收模块未开通")) {
            this.close();
            this.$alert("请先开通回收管理模块！");
          } else if (str.includes("客服即时通讯未开通")) {
            this.close();
            this.$alert("请先开通回客服即时通讯功能！");
            // this.$router.push({
            //   path: "/shopManageByTenant/tenantPages/customerService",
            // });
          } else if (str.includes("店铺未实名认证")) {
            this.close();
            this.$refs.authDialogVue.open();
          }
        });
    },
    // 点击充值
    chongzhijifen() {
      this.$refs.chongzhi.open();
      // this.$refs.paySuccess.open();
    },
    close(formName) {
      this.$emit("close");
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
.kuaijie {
  flex-wrap: wrap;
}
.kuaijie-item {
  min-width: 150px;
  // width: 100%;
  // height: 49px;
  border-radius: 4px;
  border: 1px solid $yellow;
  text-align: center;
  color: $yellow;
  padding: 10px;
  margin-right: 30px;
  margin-bottom: 10px;
  cursor: pointer;
  position: relative;
  &.active {
    color: #fff;
    background-color: #ff9717;
  }
  .xs {
    background-color: #eb8200;
    width: 33px;
    height: 17px;
    font-size: 12px;
    line-height: 16px;
    position: absolute;
    top: 0;
    right: 0;
    color: #fff;
  }
}
.center {
  text-align: center;
  margin-top: 15px;
}
.tip {
  color: red;
}
</style>
